<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <user-search
        v-if="searchData.length > 0"
        :searchData="searchData"
        @search="reload"
      />
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        :row-key="(record) => record.id"
        :columns="columns"
        :datasource="datasource"
        v-model:selection="selection"
        @update:selection="onSelectionChange"
        :scroll="{ x: 'max-content' }"
      >
        <template #toolbar>
          <slot name="toolbar"></slot>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.type === 'link'">
            <!-- <router-link :to="'/system/user-info?id=' + record.userId">{{ record.code }}</router-link> -->
            <a @click="toDetail(record, column.extra)">{{ record.code }}</a>
          </template>
          <template v-else-if="column.type === 'image'">
            <img :src="record.logo_path" class="logo" />
          </template>
          <template v-else-if="column.name === 'status_name'">
            <!-- <a-switch
              :checked="record.status == 1"
              @change="switchChange($event, column, record)"
            /> -->
            <a>
              <template v-if="record.receive_status == 0">待接收</template>
              <template v-else-if="record.receive_status == 1">同意</template>
              <template v-else-if="record.receive_status == 2">拒绝</template>
            </a>
          </template>
          <!-- <template v-else-if="column.type === 'btn'">
						<a-space>
							<a @click="actionOpts('edit', record)">编辑0</a>
							<a @click="actionOpts('del', record)">删除0</a>
						</a-space>
					</template> -->
          <template v-else-if="column.key === 'action'">
            <slot name="optBtn" :record="record"></slot>
            <div>
              <!-- 此处v-permission的值需要做处理，权限接口返回的权限前面没有“/”此处接口返回的权限开头是“/”，所以要接去后传入权限校验方法 -->
              <div
                class="premission_btn"
                v-for="item in column.param"
                v-permission="item.url"
                :key="item.url"
                @click="defineFn(item, record)"
              >
                <!-- 状态:-2删除，-1作废，0草稿，1审核中，2审核通过，3审核驳回-->
                <template v-if="record.receive_status == 0">
                  <a v-if="item.type == 'agree' || item.type == 'reject'">{{
                    item.name
                  }}</a>
                </template>
              </div>
            </div>
          </template>
          <template v-else></template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 编辑弹窗 -->
    <!-- <user-edit v-model:visible="showEdit" :data="current" @done="reload" /> -->
    <!-- 导入弹窗 -->
    <!-- <user-import v-model:visible="showImport" @done="reload" /> -->
  </div>
</template>

<script setup>
  import { ref, onMounted, nextTick } from 'vue';
  import UserSearch from './components/user-search.vue';
  import formatColumns from '@/utils/tableColumnsFormat';
  import { useRouter } from 'vue-router';
  import { actionFn } from '@/utils/action.js';
  const router = useRouter();
  const { push } = useRouter();
  const props = defineProps({
    apiFun: Function
  });
  const emit = defineEmits(['action', 'actionOpt', 'getselection']);
  // 表格实例
  const tableRef = ref(null);
  // 表格列配置
  let columns = ref([]);
  // 表格搜索动态表单
  let searchData = ref([]);
  // 表格选中数据
  const selection = ref([]);
  // 触发父级方法数组
  const emitsArr = ref([]);

  onMounted(() => {});
  // 表格数据源
  const datasource = ({ page, limit, where }) => {
    return props.apiFun({
      page,
      limit,
      page_size: limit,
      filters: {
        ...where
      }
    });
  };
  // 表头/搜索栏，数据
  props.apiFun().then(async (res) => {
    columns.value = await formatColumns(res.columns);
    searchData.value = res.searchData;
    // 生成emits数组
    /* if(columns.value[columns.value.length - 1].param && columns.value[columns.value.length - 1].param.length > 0){
	emitsArr.value = columns.value[columns.value.length - 1].param.map(item => item.type);
	} */
    hideSelection();
  });
  /* 搜索 */
  const reload = (where) => {
    selection.value = undefined;
    tableRef?.value?.reload({ page: 1, where });
  };
  // 触发父级方法
  const defineFn = (actionData, rowData) => {
    const data = {
      action_data: actionData,
      row_data: rowData
    };
    console.log(data);
    emit('action', data);
  };

  // 如果要动态控制是否开启多选列可以将 selection 赋值为 undefined
  const hideSelection = () => {
    selection.value = undefined;
  };

  // 如果要动态控制是否开启多选列可以将 selection 赋值为 undefined
  const changeSelection = (val) => {
    console.log('是否显示选择框0', val);
    if (val) {
      console.log('是否显示选择框1', val);
      selection.value = [];
    } else {
      console.log('是否显示选择框2', val);
      if (
        typeof selection.value == undefined ||
        typeof selection.value == 'object'
      ) {
        selection.value = undefined;
      } else {
        selection.value = [];
      }
    }
  };
  //选中的值发生改变是触发父组件的方法并传值
  const onSelectionChange = (selection) => {
    console.log('选择的是', selection);
    selection.value = selection;
    emit('getselection', selection);
  };
  //触发父级编辑或删除
  const actionOpts = (type, data) => {
    emit('actionOpt', type, data);
  };
  // siwtchchange
  const switchChange = async (e, column, record) => {
    const url = router.currentRoute.value.path.split('/');
    const apiUrl = `/${url[1]}/${url[2]}/quick_edit`;
    await actionFn(
      { url: apiUrl },
      { id: record.id, field: column.field, value: e ? '1' : '0' },
      reload
    );
  };

  const toDetail = (record, url) => {
    console.log('看详情');
    let r = router.currentRoute.value.path.split('/');
    let newUrl = `/${r[1]}/${r[2]}/detail`;
    console.log('newUrl', newUrl);
    push({
      path: newUrl,
      query: { code: record.code }
    });
  };
  // **重点！！这里需要使用defineExpose暴露出去**
  defineExpose({
    reload,
    changeSelection
  });
</script>

<script>
  export default {
    name: 'SystemUser'
  };
</script>

<style lang="less" scoped>
  .logo {
    width: 40px;
  }
  .premission_btn {
    display: inline-block;
    a {
      margin: 0 8px;
    }
  }
</style>
